<?php

namespace app\api\controller;

use app\api\model\Block;
use app\common\controller\Api;
use Exception;
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
use PhpOffice\PhpSpreadsheet\Reader\Xlsx;
use PhpOffice\PhpSpreadsheet\Reader\Xls;
use PhpOffice\PhpSpreadsheet\Reader\Csv;
use think\Db;
use think\db\exception\BindParamException;
use think\db\exception\DataNotFoundException;
use think\db\exception\ModelNotFoundException;
use think\db\Query;
use think\exception\DbException;
use think\exception\PDOException;
use think\exception\ValidateException;
use PhpOffice\PhpSpreadsheet\Spreadsheet;

/**
 * 公共方法
 */
class Communal extends Api
{
    // 无需登录的接口,*表示全部
    // protected $noNeedLogin = ['uplodebase','commonGrade', 'import','enSubjectList','subjectList','bigNum','saveExamImage','saveExamImages'];
    // 无需鉴权的接口,*表示全部
    // protected $noNeedRight = ['uplodebase','commonGrade', 'import','enSubjectList','subjectList','bigNum','saveExamImage','saveExamImages'];
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];
    /**
     * 导入文件首行类型
     * 支持comment/name
     * 表示注释或字段名
     */
    protected $importHeadType = 'comment';

    /**
     * 图片上传
     *
     * @return void
     */
    public function uplodebase()
    {
        if ($this->request->isPost()) {

            $file = $this->request->post('file');
            if (!$file) {
                $this->error('参数错误,请重试!');
            }
            $result = saveBase64Image($file);
            if ($result == false) $this->error('上传失败,请重试!');
            $this->success('图片上传', ['url' => $result, 'fullurl' => cdnurl($result, true)]);
        } else {
            $this->error('请求错误,请重试!');
        }
    }

    //分割图片
    public function cropBlock()
    {
        if (!$this->request->isPost()) $this->error('请求方式错误！');
        $exams_list_id = $this->request->post('exams_list_id');
        $student_id = $this->request->post('student_id');
        //分隔合并题块
        Block::cropBlock($exams_list_id, $student_id);
        $this->success('操作成功');
    }

    //公共年级
    public function commonGrade()
    {
        if (!$this->request->isGet()) $this->error('请求方式错误！');
        $list = db('common_grade')->where(['status' => 'normal'])->field('id,name')->order('weigh asc')->select();
        $this->success('公共年级列表', $list);
    }

    //年级组列表
    public function stageList()
    {
        if (!$this->request->isGet()) $this->error('请求方式错误');
        $school_id = $this->school_id ?? 1;
        $list = db('school_stage')->where(['school_id' => $school_id])->field('id,name')->order('createtime desc')->select();
        $this->success('年级组列表', $list);
    }

    //年级列表
    public function gradeList()
    {
        if (!$this->request->isGet()) $this->error('请求方式错误');
        $school_id = $this->school_id ?? 1;
        $list = db('school_grade')->where(['school_id' => $school_id])->field('id,name')->order('createtime desc')->select();
        $this->success('年级列表', $list);
    }

    //班级列表
    public function classList()
    {
        if (!$this->request->isGet()) $this->error('请求方式错误');
        $school_id = $this->school_id;
        $grade_id = $this->request->get('grade_id');
        $type = $this->request->get('type');
        $subject_id = $this->request->get('subject_id');
        $list = db('school_class')
            ->where(function ($query) use ($subject_id, $type) {
                if ($subject_id) {
                    $type = 'JX';
                    $query->where(['type' => $type, 'subject_id' => $subject_id]);
                } else {
                    if ($type) {
                        $query->where('type', $type);
                    }
                }
            })
            ->where(['school_id' => $school_id, 'grade_id' => $grade_id])->field('id,name')->order('createtime desc')->select();
        $this->success('班级列表', $list);
    }

    //教学班列表
    public function jxClassList()
    {
        if (!$this->request->isGet()) $this->error('请求方式错误');
        $school_id = $this->school_id ?? 1;
        $grade_id = $this->request->get('grade_id');
        $list = db('school_class')
            ->where(['school_id' => $school_id, 'grade_id' => $grade_id, 'type' => 'JX'])->field('id,subject_id,name')->order('createtime desc')->select();
        foreach ($list as &$value) {
            $value['subject_text'] = db('subject')->where('id', $value['subject_id'])->value('name');
        }
        $this->success('教学班列表', $list);
    }

    //科目列表
    public function subjectList()
    {
        if (!$this->request->isGet()) $this->error('请求方式错误');
        $list = db('subject')->where(['type' => 1])->field('id,name')->order('create_time desc')->select();
        $this->success('科目列表', $list);
    }

    //英文科目列表
    public function enSubjectList()
    {
        if (!$this->request->isGet()) $this->error('请求方式错误');
        $list = db('subject')->where(['type' => 2])->field('id,name')->order('create_time desc')->select();
        $this->success('英文科目列表', $list);
    }

    //角色列表
    public function userGroupList()
    {
        if (!$this->request->isGet()) $this->error('请求方式错误');
        $list = db('user_group')->where(['status' => 'normal'])->where('id', 'neq', 1)->field('id,name')->order('id asc')->select();
        $this->success('角色列表', $list);
    }

    //选考列表
    public function selectExamList()
    {
        if (!$this->request->isGet()) $this->error('请求方式错误');
        $list = db('select_exam')->where('id', 'neq', 1)->field('id,name')->order('id asc')->select();
        $this->success('选考列表', $list);
    }

    //大题题号
    public function bigNum()
    {
        if (!$this->request->isGet()) $this->error('请求方式错误');
        $list = config('site.bignum');
        $data = [];
        foreach ($list as $key => $value) {
            $data[] = [
                'id' => $key,
                'name' => $value
            ];
        }
        $this->success('大题题号', $data);
    }

    //存储答题卡图片
    public function saveExamImage()
    {
        if (!$this->request->isPost()) $this->error('请求方式错误');
        $exams_list_id = $this->request->post('exams_list_id');//考试id
        $zimage = $this->request->post('zimage');//图片url
        $key = $this->request->post('key');//图片key
        $batchnum = $this->request->post('batchnum');//批次号
        $type = $this->request->post('type');//类型：'MO'=模版，'DA'=答题卡
        if (!$exams_list_id || !$zimage || !in_array($type, ['MO', 'DA'])) $this->error('参数错误！');
        $examsList = db('exam_list')->where(['id' => $exams_list_id])->find();
        if (!$examsList) $this->error('未找到相关试卷信息！');
        $exams_id = $examsList['exams_id'];
        if (!$exams_id) $this->error('未找到相关试卷信息！');
        switch ($type) {
            case 'MO':
                $in = db('exam_images')->insertGetId([
                    'exams_id' => $exams_id,
                    'exams_list_id' => $exams_list_id,
                    'zimage' => $zimage

                ]);
                
                break;
            case 'DA':
                if (!$key) $this->error('参数错误！');
                //考卷增加扫描数
                if (!db('exam_paper_images')->where(['key' => $key])->find()) {
                    db('exam_list')->where('id', $exams_list_id)->setInc('scannum', 1);
                }
                $in = db('exam_paper_images')->insertGetId([
                    'exams_id' => $exams_id,
                    'exams_list_id' => $exams_list_id,
                    'school_id' => $this->school_id,
                    'image' => $zimage,
                    'key' => $key,
                    'batchnum' => $batchnum,
                    'user_id' => $examsList['user_id'],
                    'createtime' => time()
                ]);

                db('exam_list')->where('id', $exams_list_id)->update(['scancard' => 1, 'status' => 1]);
                break;
        }
        if ($in) {
            $this->success('操作成功', $in);
        } else {
            $this->error('操作失败！');
        }
    }

    //存储学生答题卡图片
    public function saveExamImages()
    {
        if (!$this->request->isPost()) $this->error('请求方式错误');
        $exams_list_id = $this->request->post('exams_list_id');
        $image = $this->request->post('image');
        $key = $this->request->post('key');
        if (!$exams_list_id || !$image || !$key) $this->error('参数错误！');
        $exams_id = db('exam_list')->where(['id' => $exams_list_id])->value('exams_id');
        if (!$exams_id) $this->error('未找到相关试卷信息！');
        $in = db('exam_image')->insertGetId([
            'exams_id' => $exams_id,
            'exams_list_id' => $exams_list_id,
            'image' => $image,
            'key' => $key
        ]);
        if ($in) {
            //考卷增加扫描数
            db('exam_list')->where('id', $exams_list_id)->setInc('scannum', 1);
            $this->success('操作成功', $in);
        } else {
            $this->error('操作失败！');
        }
    }

    //更新答题卡图片
    public function upExamImage()
    {
        if (!$this->request->isPost()) $this->error('请求方式错误');
        $id = $this->request->post('id');
        $zimage = $this->request->post('zimage');
        if (!$id || !$zimage) $this->error('参数错误！');
        $image = db('exam_images')->where(['id' => $id])->find();
        if (!$image) $this->error('未找到相关答题卡信息！');
        $up = db('exam_images')->where(['id' => $id])->update([
            'zimage' => $zimage
        ]);
        if ($up) {
            $this->success('操作成功');
        } else {
            $this->error('操作失败！');
        }
    }

    //更新答题卡图片区域信息
    public function upExamImageContent()
    {
        if (!$this->request->isPost()) $this->error('请求方式错误');
        $id = $this->request->post('id');
        if (!$id) $this->error('参数错误！');
        $content = $this->request->param('content/a');
        if (!is_array($content)) $this->error('参数格式错误！');
        $image = db('exam_images')->where(['id' => $id])->find();
        if (!$image) $this->error('未找到相关答题卡信息！');
        $up = db('exam_images')->where(['id' => $id])->update([
            'content' => json_encode($content)
        ]);

        if ($up) {
            $this->success('操作成功');
        } else {
            $this->error('操作失败！');
        }
    }

    //读取列表
    public function getExamImage()
    {
        if (!$this->request->isPost()) $this->error('请求方式错误');
        $exams_list_id = $this->request->post('exams_list_id');
        $exams_id = db('exam_list')->where(['id' => $exams_list_id])->value('exams_id');
        if (!$exams_id) $this->error('未找到相关试卷信息！');
        $list = db('exam_images')->where(['exams_id' => $exams_id, 'exams_list_id' => $exams_list_id])->order('isindex desc,id asc')->select();
        $this->success('答题卡列表', $list);
    }

    //设置模版首页
    public function setExamImageIsindex()
    {
        if (!$this->request->isPost()) $this->error('请求方式错误');
        $id = $this->request->post('id');
        $exams_list_id = $this->request->post('exams_list_id');
        if (!$id || !$exams_list_id) $this->error('参数错误！');
        db('exam_images')->where(['id' => $id])->update(['isindex'=>1]);
        db('exam_images')->where(['exams_list_id' => $exams_list_id])->where('id','neq',$id)->update(['isindex'=>0]);
        $this->success('操作成功');
    }
}
